import { getBaseUrl } from "."

//获取 uni.login code
export const getWeixinCode = () => {
	return new Promise((resolve, reject) => {
		// uni.login非异步，所以用Promise包装
		uni.login({
			provider: 'weixin',
			success: (res) => {
				resolve(res.code)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 获取节点信息
export function getNodeInfo(
	nodeName : string,
	instance : any
) : Promise<UniApp.NodeInfo | UniApp.NodeInfo[]> {
	return new Promise((resovle, reject) => {
		try {
			const query : UniApp.SelectorQuery = uni.createSelectorQuery().in(instance)
			query
				.selectAll(nodeName)
				.boundingClientRect((result : UniApp.NodeInfo | UniApp.NodeInfo[]) => {
					resovle(result)
				})
				.exec()
		} catch (err) {
			reject(err)
		}
	})
}

/**
 * 预览图片
 */
export function previewImage(imageList : string[], current : number, handlerFnc ?: {
	success ?: () => void;
	complete ?: () => void;
}) : void {

	uni.previewImage({
		urls: imageList,
		current,
		success: handlerFnc ? handlerFnc.success : () => { },
		complete: handlerFnc ? handlerFnc.complete : () => { }
	})
}


// 消息订阅
export function subscribeMessage(tmplIds : string[]) : Promise<void> {
	return new Promise((resovle, reject) => {
		uni.requestSubscribeMessage({
			tmplIds,
			success() : void {
				resovle();
			},
			fail() : void {
				reject();
			}
		})
	})
}

/**
 * 获取导航栏配置数据
 * @return 
 */
export function getNavbarConfig() {
	const res = uni.getSystemInfoSync();
	// 获取手机顶部状态栏的高度
	const statusBarHeight = res.statusBarHeight || 0;

	// 获取导航栏的高度（手机状态栏高度 + 胶囊高度 + 胶囊的上下间距）
	const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2;

	// 计算顶部图标距离
	const topIconDistance = statusBarHeight + navBarHeight;

	return {
		navBarHeight,
		topIconDistance
	}
}

/**
 * 判断是否有安全区域
 * @return 
 */
export function isSafeArea() {
	const info = uni.getSystemInfoSync();
	return info.safeAreaInsets && info.safeAreaInsets.bottom > 0;
}

